<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-header">
        <h2>后台管理系统</h2>
      </div>
      <el-form ref="loginForm" :model="form" :rules="rules">
        <el-form-item prop="username">
          <el-input
            v-model="form.username"
            prefix-icon="el-icon-user"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            prefix-icon="el-icon-lock"
            placeholder="请输入密码"
            type="password"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            style="width: 100%"
            :loading="loading"
            @click="handleLogin"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { loginApi } from "@/api";
// import { ElMessage } from "element-plus";

export default {
  setup() {
    const router = useRouter();
    const store = useStore();
    const loginForm = ref(null);
    const loading = ref(false);

    const form = ref({
      username: "admin",
      password: "123456",
    });

    const rules = {
      username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
      password: [{ required: true, message: "请输入密码", trigger: "blur" }],
    };

    const handleLogin = () => {
      loginForm.value.validate((valid) => {
        if (!valid) return;

        loading.value = true;
        loginApi(form.value)
          .then((res) => {
            store.dispatch("login", {
              token: res.data.token,
              userInfo: res.data.userInfo,
            });
            router.push("/dashboard");
          })
          .catch(() => {
            loading.value = false;
          });
      });
    };

    return {
      form,
      rules,
      loading,
      loginForm,
      handleLogin,
    };
  },
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #1e5799 0%, #207cca 51%, #2989d8 100%);
}

.login-card {
  width: 400px;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #303133;
  font-weight: 500;
}
</style>
